package com.sun.servlet;


import com.sun.service.WxService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

@WebServlet("/wx")
public class WxServlet extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String signature = req.getParameter("signature");
		String timestamp = req.getParameter("timestamp");
		String nonce = req.getParameter("nonce");
		String echostr = req.getParameter("echostr");
		// 校验请求
		if (WxService.check(timestamp, nonce, signature)) {
			System.out.println("接入成功!");
			PrintWriter out = resp.getWriter();
			out.print(echostr);
			out.flush();
			out.close();
		} else {
			System.out.println("接入失败!");
		}
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 处理消息事件
		Map<String, String> requestMap = WxService.parseRequest(req.getInputStream());
		System.out.println(requestMap);
		String respXml = WxService.getResponse(requestMap);
		System.out.println(respXml);
		PrintWriter out = resp.getWriter();
		out.print(respXml);
		out.flush();
		out.close();
	}
}
